package com.chatplus.application.listener;

import cn.hutool.core.bean.BeanUtil;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.domain.entity.account.UserEntity;
import com.chatplus.application.domain.entity.basedata.PowerLogsEntity;
import com.chatplus.application.domain.entity.chat.ChatHistoryEntity;
import com.chatplus.application.domain.entity.chat.ChatItemEntity;
import com.chatplus.application.domain.entity.chat.ChatModelEntity;
import com.chatplus.application.domain.notification.PowerLogNotification;
import com.chatplus.application.enumeration.AiPlatformEnum;
import com.chatplus.application.service.account.UserProductLogService;
import com.chatplus.application.service.account.UserService;
import com.chatplus.application.service.basedata.PowerLogsService;
import com.chatplus.application.service.chat.ChatHistoryService;
import com.chatplus.application.service.chat.ChatItemService;
import com.chatplus.application.service.chat.ChatModelService;
import com.chatplus.application.web.notification.NotificationListener;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 算力日志监听器
 */
@Component
public class PowerLogNotificationListener {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(PowerLogNotificationListener.class);
    private final UserService userService;
    private final PowerLogsService powerLogsService;
    private final UserProductLogService userProductLogService;
    private final ChatHistoryService chatHistoryService;
    private final ChatItemService chatItemService;
    private final ChatModelService chatModelService;

    public PowerLogNotificationListener(UserService userService,
                                        PowerLogsService powerLogsService,
                                        UserProductLogService userProductLogService,
                                        ChatHistoryService chatHistoryService,
                                        ChatItemService chatItemService,
                                        ChatModelService chatModelService) {
        this.userService = userService;
        this.powerLogsService = powerLogsService;
        this.userProductLogService = userProductLogService;
        this.chatHistoryService = chatHistoryService;
        this.chatItemService = chatItemService;
        this.chatModelService = chatModelService;
    }

    @NotificationListener(notification = PowerLogNotification.class)
    public void handlePowerLogNotification(PowerLogNotification notification) {
        try {
            PowerLogsEntity powerLogsEntity = BeanUtil.copyProperties(notification, PowerLogsEntity.class);
            UserEntity userEntity = userService.getById(notification.getUserId());
            if (userEntity == null) {
                LOGGER.message("用户不存在").context("notification", notification).error();
                return;
            }
            // -----------------以下为自动备注----------------
            handleRemark(powerLogsEntity, notification);
            // -----------------以上为自动备注----------------
            powerLogsEntity.setUsername(userEntity.getUsername());
            powerLogsEntity.setBalance(userProductLogService.getUserChatPower(userEntity.getId()));
            powerLogsService.save(powerLogsEntity);
        } catch (Exception e) {
            LOGGER.message("处理算力日志通知异常").context("notification", notification).exception(e).error();
        }
    }

    private void handleRemark(PowerLogsEntity powerLogsEntity, PowerLogNotification notification) {
        String notificationRemark = notification.getRemark();
        String remark = "";
        AiPlatformEnum platform = notification.getPlatform();
        if (platform == null) {
            return;
        }
        switch (platform) {
            case SD_LOCAL, SD_STABILITY:
                remark = String.format("SD 绘画扣除算力[%s]", notification.getAmount());
                powerLogsEntity.setModel("SD绘画");
                break;
            case MJ:
                remark = String.format("MJ 绘画扣除算力[%s]", notification.getAmount());
                powerLogsEntity.setModel("MJ绘画");
                break;
            default:
                if (notification.getHistoryItemId() != null) {
                    List<ChatHistoryEntity> chatHistoryEntityList = chatHistoryService.getHistoryByItemId(notification.getHistoryItemId());
                    if (chatHistoryEntityList == null || chatHistoryEntityList.isEmpty()) {
                        LOGGER.message("聊天记录不存在").context("notification", notification).error();
                        return;
                    }
                    Long promptTokens = 0L;
                    Long replyTokens = 0L;
                    String modelName = "不存在";
                    for (ChatHistoryEntity chatHistoryEntity : chatHistoryEntityList) {
                        if (chatHistoryEntity == null) {
                            continue;
                        }
                        if (chatHistoryEntity.getType().equals("prompt")) {
                            promptTokens = chatHistoryEntity.getTokens();
                        }
                        if (chatHistoryEntity.getType().equals("reply")) {
                            replyTokens = chatHistoryEntity.getTokens();
                        }
                    }
                    ChatItemEntity chatItemEntity = chatItemService.getChatItemByChatId(chatHistoryEntityList.getFirst().getChatId());
                    if (chatItemEntity != null) {
                        ChatModelEntity chatModelEntity = chatModelService.getById(chatItemEntity.getModelId());
                        if (chatModelEntity != null) {
                            modelName = chatModelEntity.getName();
                            powerLogsEntity.setModel(chatModelEntity.getValue());
                        }
                    }
                    remark = String.format("模型名称：%s, 提问长度：%d，回复长度：%d", modelName, promptTokens, replyTokens);
                }
                break;
        }
        if (StringUtils.isEmpty(notificationRemark)) {
            powerLogsEntity.setRemark(remark);
        } else {
            powerLogsEntity.setRemark(notificationRemark);
        }
    }

}
